#pragma once

#include <chrono>
#include <cstdint>
#include <string>
#include <unordered_map>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <mutex>

namespace TimeUtils {


// 使用单调时钟，不受系统时间调整影响
using Clock = std::chrono::steady_clock;
using Milliseconds = std::chrono::milliseconds;
using TimePoint = Clock::time_point;

/**
 * @brief 获取从某个固定点开始的当前时间（毫秒）
 * @return 当前时间戳（毫秒）
 */
inline uint64_t get_steady_time_ms() {
    auto now = Clock::now();
    auto duration = now.time_since_epoch();
    return std::chrono::duration_cast<Milliseconds>(duration).count();
}

/**
 * @brief 高性能计时器类
 */
class Timer {
private:
    TimePoint start_time_;
    std::string name_;
    
public:
    explicit Timer(const std::string& name = "") 
        : start_time_(Clock::now()), name_(name) {}
    
    /**
     * @brief 重置计时器
     */
    void reset() {
        start_time_ = Clock::now();
    }
    
    /**
     * @brief 获取经过的时间（毫秒）
     */
    uint64_t elapsed_ms() const {
        auto now = Clock::now();
        return std::chrono::duration_cast<Milliseconds>(now - start_time_).count();
    }
    
    /**
     * @brief 获取经过的时间（秒）
     */
    double elapsed_seconds() const {
        return elapsed_ms() / 1000.0;
    }
    
    /**
     * @brief 检查是否超时
     * @param timeout_ms 超时时间（毫秒）
     */
    bool timeout(uint64_t timeout_ms) const {
        return elapsed_ms() >= timeout_ms;
    }
    
    /**
     * @brief 获取计时器名称
     */
    const std::string& name() const {
        return name_;
    }
    
    /**
     * @brief 打印经过的时间
     */
    void print_elapsed(const std::string& message = "") const {
        std::cout << "[Timer" << (name_.empty() ? "" : " " + name_) << "] "
                  << message << " - 耗时: " << elapsed_ms() << "ms" << std::endl;
    }
};

/**
 * @brief 自动记录作用域时间的RAII类，Resource Acquisition Is Initialization
 * 对象生命周期，在构造函数中获取资源，在析构函数中释放资源。
 */
class ScopedTimer {
private:
    Timer timer_;
    std::string scope_name_;
    
public:
    explicit ScopedTimer(const std::string& scope_name = "")
        : timer_(scope_name), scope_name_(scope_name) {
        if (!scope_name_.empty()) {
            std::cout << "↗ 进入作用域: " << scope_name_ << std::endl;
        }
    }
    
    ~ScopedTimer() {
        auto elapsed = timer_.elapsed_ms();
        if (!scope_name_.empty()) {
            std::cout << "↘ 离开作用域: " << scope_name_ 
                      << " - 总耗时: " << elapsed << "ms" << std::endl;
        }
    }
    
    // 禁止拷贝
    ScopedTimer(const ScopedTimer&) = delete;
    ScopedTimer& operator=(const ScopedTimer&) = delete;
};

/**
 * @brief 性能监控器（统计多次执行）
 */
class PerformanceMonitor {
private:
    std::string name_;
    uint64_t total_time_ = 0;
    uint64_t count_ = 0;
    uint64_t min_time_ = UINT64_MAX;
    uint64_t max_time_ = 0;
    
public:
    explicit PerformanceMonitor(const std::string& name = "") : name_(name) {}
    
    void record(uint64_t duration_ms) {
        total_time_ += duration_ms;
        count_++;
        min_time_ = std::min(min_time_, duration_ms);
        max_time_ = std::max(max_time_, duration_ms);
    }
    
    void reset() {
        total_time_ = 0;
        count_ = 0;
        min_time_ = UINT64_MAX;
        max_time_ = 0;
    }
    
    void print_stats() const {
        if (count_ == 0) return;
        
        std::cout << "=== 性能统计: " << (name_.empty() ? "未命名" : name_) << " ===" << std::endl;
        std::cout << "执行次数: " << count_ << std::endl;
        std::cout << "总耗时: " << total_time_ << "ms" << std::endl;
        std::cout << "平均耗时: " << (total_time_ / count_) << "ms" << std::endl;
        std::cout << "最短耗时: " << min_time_ << "ms" << std::endl;
        std::cout << "最长耗时: " << max_time_ << "ms" << std::endl;
        std::cout << "=============================" << std::endl;
    }
    
    uint64_t average_time() const {
        return count_ > 0 ? total_time_ / count_ : 0;
    }
};

/**
 * @brief 全局性能监控管理器
 */
class PerformanceManager {
private:
    static std::unordered_map<std::string, PerformanceMonitor> monitors_;
    
public:
    static void record(const std::string& name, uint64_t duration_ms) {
        monitors_[name].record(duration_ms);
    }
    
    static void print_all_stats() {
        std::cout << "\n======= 全局性能统计 =======" << std::endl;
        for (auto& [name, monitor] : monitors_) {
            monitor.print_stats();
        }
    }
    
    static void reset_all() {
        monitors_.clear();
    }
};
// 全局时间戳管理器
class TimestampManager {
private:
    static std::unordered_map<std::string, uint64_t> timestamps_;
    static std::mutex mutex_;

public:
    /**
     * @brief 只获取当前时间，不记录到映射中(全局)
     * @return 当前时间戳（毫秒）
     */
    static uint64_t get_current_time() {
        return TimeUtils::get_steady_time_ms();
    }
    /**
     * @brief 记录时间戳并返回时间戳值
     * @param key 时间戳标识符
     * @return 记录的时间戳（毫秒）
     */
    static uint64_t record(const std::string& key) {
        std::lock_guard<std::mutex> lock(mutex_);
        uint64_t current_time = get_steady_time_ms();
        timestamps_[key] = current_time;
        std::cout << "📌 记录时间戳: " << key << " = " << current_time << "ms" << std::endl;
        return current_time;
    }
    /**
     * @brief 记录时间戳（不打印信息，适合频繁调用）
     * @param key 时间戳标识符
     * @return 记录的时间戳（毫秒）
     */
    static uint64_t record_quiet(const std::string& key) {
        std::lock_guard<std::mutex> lock(mutex_);
        uint64_t current_time = get_steady_time_ms();
        timestamps_[key] = current_time;
        return current_time;
    }
    // 获取时间戳
    static uint64_t get(const std::string& key) {
        std::lock_guard<std::mutex> lock(mutex_);
        auto it = timestamps_.find(key);
        if (it != timestamps_.end()) {
            return it->second;
        }
        throw std::runtime_error("时间戳未找到: " + key);
    }
    
    // 计算时间差
    static uint64_t calculate_difference(const std::string& key1, const std::string& key2) {
        uint64_t time1 = get(key1);
        uint64_t time2 = get(key2);
        return std::abs(static_cast<int64_t>(time2 - time1));
    }
    
    // 打印时间差
    static void print_difference(const std::string& key1, const std::string& key2) {
        uint64_t diff = calculate_difference(key1, key2);
        std::cout << "⏱️  时间差 [" << key1 << " → " << key2 << "]: " 
                  << diff << "ms" << std::endl;
    }
    
    // 清空所有时间戳
    static void clear() {
        std::lock_guard<std::mutex> lock(mutex_);
        timestamps_.clear();
    }
    /**
     * @brief 获取所有记录的时间戳
     * @return 时间戳映射的拷贝
     */
    static std::unordered_map<std::string, uint64_t> get_all_timestamps() {
        std::lock_guard<std::mutex> lock(mutex_);
        return timestamps_;
    }

    /**
     * @brief 打印所有记录的时间戳
     */
    static void print_all_timestamps() {
        std::lock_guard<std::mutex> lock(mutex_);
        std::cout << "\n======= 所有记录的时间戳 =======" << std::endl;
        for (const auto& [key, timestamp] : timestamps_) {
            std::cout << "Key: " << key << ", Timestamp: " << timestamp << "ms" << std::endl;
        }
        std::cout << "===============================" << std::endl;
    }

};



// 静态成员声明
extern std::unordered_map<std::string, PerformanceMonitor> PerformanceManager::monitors_;
extern std::unordered_map<std::string, uint64_t> TimestampManager::timestamps_;
extern std::mutex TimestampManager::mutex_;




} // namespace TimeUtils

// 宏定义，方便使用
#define SCOPED_TIMER(name) TimeUtils::ScopedTimer scoped_timer_##__LINE__(name)
#define TIME_SCOPE(name) SCOPED_TIMER(name)
#define TIME_FUNCTION() SCOPED_TIMER(__FUNCTION__)




